package com.xnyzc.lhy.order.entity.common.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.entity.netty.NettyDriverOrderInfo;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EDriverStatus;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.EOrderType;
import com.xnyzc.lhy.common.penum.EUserTypeNum;
import com.xnyzc.lhy.common.penum.gould.EGould;
import com.xnyzc.lhy.common.penum.order.EOrderCostType;
import com.xnyzc.lhy.common.penum.order.EOrderStatus;
import com.xnyzc.lhy.common.penum.order.ETabType;
import com.xnyzc.lhy.common.penum.vehicle.ECallVehType;
import com.xnyzc.lhy.common.penum.vehicle.EvehicleType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.DateUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.nio.entity.netty.NettyUserOrderInfo;
import com.xnyzc.lhy.order.entity.area.OaSysArea;
import com.xnyzc.lhy.order.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.order.entity.gps.OaDVehicleGps;
import com.xnyzc.lhy.order.entity.order.*;
import com.xnyzc.lhy.order.entity.param.order.InitiatePaymentParam;
import com.xnyzc.lhy.order.entity.param.order.OrderParam;
import com.xnyzc.lhy.order.entity.result.vehicle.VehicleBrand;
import com.xnyzc.lhy.order.entity.system.OaSysBillRules;
import com.xnyzc.lhy.order.entity.system.OaSysGlobalConfig;
import com.xnyzc.lhy.order.entity.user.OaCUser;
import com.xnyzc.lhy.order.entity.user.OaDUser;
import com.xnyzc.lhy.order.entity.user.OaDUserInfo;
import com.xnyzc.lhy.order.entity.vehicle.OaDDriverVehicle;
import com.xnyzc.lhy.order.entity.vehicle.OaSysVehicle;
import com.xnyzc.lhy.order.feign.amap.IAmapService;
import com.xnyzc.lhy.order.mapper.area.OaSysAreaMapper;
import com.xnyzc.lhy.order.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.order.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.order.mapper.order.OaDOrderMapper;
import com.xnyzc.lhy.order.mapper.order.OaOrderEvaluationMapper;
import com.xnyzc.lhy.order.mapper.system.OaSysBillRulesMapper;
import com.xnyzc.lhy.order.mapper.system.OaSysGlobalConfigMapper;
import com.xnyzc.lhy.order.mapper.user.OaCUserMapper;
import com.xnyzc.lhy.order.mapper.user.OaDUserInfoMapper;
import com.xnyzc.lhy.order.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.order.mapper.vehicle.OaDDriverVehicleMapper;
import com.xnyzc.lhy.order.mapper.vehicle.OaSysVehicleMapper;
import com.xnyzc.lhy.order.mapper.vehicle.OaSysVehicleMdictMapper;
import com.xnyzc.lhy.order.service.order.IOaCOrderPersonalOfficialService;
import com.xnyzc.lhy.order.service.order.IOaCOrderPersonalService;
import com.xnyzc.lhy.order.service.order.IOaOrderOtherPriceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xnyzc.lhy.common.entity.ParameterEnum.ONE;
import static com.xnyzc.lhy.common.entity.ParameterEnum.THREE;
import static com.xnyzc.lhy.common.entity.ParameterEnum.ZERO;

/**
 * @Author: huxuekuo
 * @Date: 2019-07-23 18:00
 * @Description:
 */
@Component
@Slf4j
public class OrderCommon {

    @Autowired
    private OaCOrderPersonalMapper personalMapper;

    @Autowired
    OaDOrderMapper orderMapper;

    @Autowired
    IOaCOrderPersonalService personalService;

    @Autowired
    IOaCOrderPersonalOfficialService personalOfficiallService;

    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;
    /**
     * 区域
     */
    @Autowired
    private OaSysAreaMapper areaMapper;

    /**
     * 乘客用户表
     */
    @Autowired
    private OaCUserMapper userMapper;

    @Autowired
    private IOaOrderOtherPriceService orderOtherPriceService;

    @Autowired
    private OaSysVehicleMapper sysVehicleMapper;

    @Autowired
    private OaDDriverVehicleMapper driverVehicleMapper;

    @Autowired
    private OaDUserMapper dUserMapper;

    @Autowired
    private OaDUserInfoMapper dUserInfoMapper;

    @Autowired
    private OaSysVehicleMdictMapper mdictMapper;

    @Autowired
    private RedisCommon redisCommon;

    @Autowired
    private OaSysDictMapper sysDictMapper;

    @Autowired
    private OaOrderEvaluationMapper orderEvaluationMapper;

    @Autowired
    private OaSysGlobalConfigMapper globalConfigMapper;

    @Autowired
    private IAmapService amapService;

    @Autowired
    private OaSysDictMapper oaSysDictMapper;

    @Autowired
    private OaSysBillRulesMapper oaSysBillRulesMapper;


    /**
     * 根据订单号查询人员订单信息
     */
    public OaCOrder selectOn(String orderNo) {
        OaCOrder oaCOrder = null;
        Qw qw = Qw.create();
        qw.eq("order_no", orderNo);
        //自费
        List<OaCOrderPersonal> oaCOrderPersonalList = personalMapper.selectList(qw);

        if (CheckUtil.collectionIsEmpty(oaCOrderPersonalList)) {
            return null;
        }
        oaCOrder = oaCOrderPersonalList.get(0);
        oaCOrder.setPassengerPhoneSuffix(oaCOrderPersonalList.get(0).getPassengerPhoneSuffix());
        oaCOrder.setPassengerPhone(oaCOrderPersonalList.get(0).getPassengerPhone());
        oaCOrder.setId(oaCOrderPersonalList.get(0).getPersonalId());
        oaCOrder.setServiceId(getServiceId());
        oaCOrder.setTid(getTid(oaCOrder.getDriverId() + ""));
        oaCOrder.setOrderType(oaCOrderPersonalList.get(0).getOrderType());
        return oaCOrder;
    }


    public OrderCommon() {
    }

    /**
     * 更改订单状态
     *
     * @param order 订单父类
     * @return
     */
    public boolean updateOrder(OaCOrder order) {
//        if (order.getOrderNo().contains(EOrderType.ZFJC.getValue())) {
//            //更改自费
//            OaCOrderPersonal personal = new OaCOrderPersonal();
//            personal.setPersonalId(order.getId());
//            BeanUtils.copyProperties(order, personal);
//            if (CheckUtil.objIsEmpty(personal.getPersonalId())) {
//                QueryWrapper<OaCOrderPersonal> wrapper = new QueryWrapper<>();
//                wrapper.eq(OaCOrderPersonal.ORDER_NO, order.getOrderNo());
//                List<OaCOrderPersonal> personalPriceList = oaCOrderPersonalMapper.selectList(wrapper);
//                personal.setPersonalId(personalPriceList.get(0).getPersonalId());
//            }
//            int i = personalMapper.updateById(personal);
//            return i > 0;
//        }
//        return false;
        // FIXME 检查以上代码对功能的影响
        return true;
    }

    /**
     * 验证订单ID合法性
     *
     * @return
     */
    public boolean orderNo(String orderNo) {
        return orderMapper.selectById(orderNo) != null ? true : false;
    }


    /**
     * 将用户下单的数据回填到用户订单表
     *
     * @return
     */
    public OaCOrder rewrite(OrderParam oaDOrder) {
        Date date = new Date();
        long tokenUserId = TokenUtil.getTokenUserId();
        //一波疯狂的数据回填,生成人员订单信息
        OaCOrder oaCOrder = new OaCOrder();
        oaCOrder.setMilageDistance(new BigDecimal(0));
        oaCOrder.setStartLat(oaDOrder.getFlat());
        oaCOrder.setStartLng(oaDOrder.getFlng());
        oaCOrder.setEndLng(oaDOrder.getTlng());
        oaCOrder.setEndLat(oaDOrder.getTlat());
        oaCOrder.setStartAddress(oaDOrder.getStartAddress());
        oaCOrder.setEndAddress(oaDOrder.getEndAddress());
        oaCOrder.setUserId(tokenUserId);
        oaCOrder.setOrderType(oaDOrder.getCallCarType());
        //默认等待应答
        oaCOrder.setOrderStatus(0);
        oaCOrder.setCreateUser(tokenUserId + "");
        oaCOrder.setUpdateTime(date);
        oaCOrder.setCreateTime(date);
        oaCOrder.setUpdateUser(tokenUserId + "");
        oaCOrder.setUserId(tokenUserId);
        oaCOrder.setOrderNo(oaDOrder.getOrderNo());
        oaCOrder.setTag(TokenUtil.getTag());
        oaCOrder.setDistanceFee(new BigDecimal(0));
        oaCOrder.setDurationFee(new BigDecimal(0));
        oaCOrder.setTotalFee(new BigDecimal(0));
        oaCOrder.setMileageFee(new BigDecimal(0));
        oaCOrder.setDrawFee(new BigDecimal(0));
        oaCOrder.setTotalFee(new BigDecimal(0));
        oaCOrder.setDurationTime(new BigDecimal(0));
        oaCOrder.setMilageDistance(new BigDecimal(0));
        oaCOrder.setOrderStatus(EOrderStatus.waitingResponse.getType());
        oaCOrder.setEstimatePrice(oaDOrder.getEstimatePrice());
        oaCOrder.setAppointment(date);
        if (CheckUtil.strIsEmpty(oaDOrder.getPassengerPhone())) {
            OaCUser oaCUser = userMapper.selectById(tokenUserId);
            oaCOrder.setPassengerPhone(oaCUser.getUserPhone());
            oaDOrder.setPassengerPhone(oaCUser.getUserPhone());
        } else {
            oaCOrder.setPassengerPhone(oaDOrder.getPassengerPhone());
        }
        String vehicleId = oaDOrder.getVehId();
        if (CheckUtil.strIsNotEmpty(vehicleId)) {
            oaCOrder.setVehicleId(Long.valueOf(vehicleId));
        }
        oaCOrder.setOrderTime(date);
        oaCOrder.setClng(oaDOrder.getClng());
        oaCOrder.setClat(oaDOrder.getClat());
        //获取城市AD_code
        String cityId = oaDOrder.getCityId();
        OaSysArea oaSysArea = areaMapper.selectOne(Qw.create()
                .eq(OaSysArea.CITY_CODE, cityId)
                .eq(OaSysArea.TYPE, THREE.getType()));
        if (!CheckUtil.objIsEmpty(oaSysArea)) {
            oaCOrder.setCityId(oaSysArea.getAdCode());
        }
        return oaCOrder;
    }


    /**
     * 封装乘客信息
     *
     * @return
     */
    public NettyDriverOrderInfo getUserMessage(OrderParam pOrder, OaDVehicleGps gps) {
        //查询乘客信息
        NettyDriverOrderInfo result = new NettyDriverOrderInfo();
        result.setOrderNo(pOrder.getOrderNo());
        result.setStartAddress(pOrder.getStartAddress());
        result.setEndAddress(pOrder.getEndAddress());
        String vehType = CheckUtil.strIsEmpty(pOrder.getCarpoolSerialNo()) ? MessageConstant.ORDER_TYPE_ONE : MessageConstant.ORDER_TYPE_TWO;
        result.setCallVehType(vehType);
        result.setStartLat(pOrder.getFlat());
        result.setStartLng(pOrder.getFlng());
        result.setEndLat(pOrder.getTlat());
        result.setEndLng(pOrder.getTlng());
        result.setOrderStatus(4);
        //猎鹰需要ID
        result.setTid(getTid(gps.getDriverId() + ""));
        result.setGpsId(getGpsId(gps.getDriverId() + ""));
        result.setServiceId(getServiceId());
        //计算司机到开始地位置
        String number = "";
        OaDVehicleGps oaDVehicleGps = JSON.parseObject(redisCommon.getStr(RedisPrefixConstant.GPS_VEH_KEY_PREFIX + gps.getDriverId()), OaDVehicleGps.class);
        if (!CheckUtil.objIsEmpty(oaDVehicleGps)) {
            Map<String, String> strategy = amapService.getDistanceAndDuration(oaDVehicleGps.getLng() + "," + oaDVehicleGps.getLat(), result.getStartLng() + "," + result.getStartLat());
            if (CheckUtil.mapIsNotEmpty(strategy)) {
                number = strategy.get(EGould.gouldDistance.getValue());
                result.setDistance(number);
                result.setDistanceTime(strategy.get(EGould.gouldDuration.getValue()));
                result.setGouldDistanceKm(strategy.get(EGould.gouldDurationKm.getValue()));
            }
        }
        result.setMsg("来订单了,据您" + number + "从" + result.getStartAddress() + "到" + result.getEndAddress() + "请尽快前往乘客上车地点接送乘客");

        try {
            result.setTime(CheckUtil.objIsEmpty(pOrder.getAppointmentTime()) ? DateUtil.getChineseDate(null) : DateUtil.getChineseDate(pOrder.getAppointmentTime()));
        } catch (ParseException e) {
        }
        return result;
    }

    /**
     * @param fee
     * @return
     */
    public BigDecimal validationBigDecimal(String fee) {
        BigDecimal fees = new BigDecimal(ZERO.getTypeName());
        if (CheckUtil.strIsEmpty(fee) && !StringUtils.isNumeric(fee)) {
            return fees;
        }
        fees = new BigDecimal(fee);
        return fees;
    }

    /**
     * 添加其他金额
     *
     * @param price   其他金额实体类
     * @param fee     金额
     * @param feeType 金额类型
     */
    public BigDecimal addOtherPrice(OaOrderOtherPrice price, String fee, Integer feeType, String remark) {
        BigDecimal fees = validationBigDecimal(fee);
        Date date = new Date();
        price.setUpdateUser(price.getCreateUser());
        price.setOtherId(IDUtil.nextId());
        price.setUpdateTime(date);
        price.setCreateTime(date);
        price.setCostAmount(fees);
        price.setCostType(feeType);
        price.setCostRemark(remark);
        price.setTag(TokenUtil.getTag());
        orderOtherPriceService.save(price);
        return fees;
    }


    /**
     * 获取其他费用总金额
     *
     * @param paymentParam
     * @param driverId
     * @return
     */
    public BigDecimal getOtherPriceTotalFee(OaCOrder oaCOrder, InitiatePaymentParam paymentParam, Long driverId) {
        OaOrderOtherPrice price = new OaOrderOtherPrice();
        price.setOrderNo(paymentParam.getOrderNo());
        price.setCreateUser(driverId);
        String remark = paymentParam.getRemark();
        // 判断输入的金额是否正确
        if (CheckUtil.objIsNotEmpty(oaCOrder.getRulesId())) {
            OaSysBillRules rules = oaSysBillRulesMapper.selectById(oaCOrder.getRulesId());
            if (CheckUtil.objIsNotEmpty(rules)) {
                BigDecimal validationBridge = validationBigDecimal(paymentParam.getBridgeFee());
                if (validationBridge.compareTo(rules.getTollFee()) == 1) {
                    throw PangException.create(EErrorCode.bridgeError.getValue(), MessageConstant.BRIDGE_ERROR + rules.getTollFee() + MessageConstant.MONEY_NAME);
                }
                BigDecimal validationHighSpeed = validationBigDecimal(paymentParam.getHighSpeedFee());
                if (validationHighSpeed.compareTo(rules.getHighSpeedFee()) != -1) {
                    throw PangException.create(EErrorCode.bridgeError.getValue(), MessageConstant.HIGH_ERROR + rules.getHighSpeedFee() + MessageConstant.MONEY_NAME);
                }
                BigDecimal validationParking = validationBigDecimal(paymentParam.getParkingFee());
                if (validationParking.compareTo(rules.getParkFee()) != -1) {
                    throw PangException.create(EErrorCode.bridgeError.getValue(), MessageConstant.PARKING_ERROR + rules.getParkFee() + MessageConstant.MONEY_NAME);
                }
            }
        } else {
            throw PangException.create(EErrorCode.noData);
        }
        //设置停车费
        BigDecimal bridgeFee = this.addOtherPrice(price, paymentParam.getBridgeFee(), EOrderCostType.bridgeFee.getType(), remark);
        //设置高速费
        BigDecimal highSpeedFee = this.addOtherPrice(price, paymentParam.getHighSpeedFee(), EOrderCostType.highSpeedFee.getType(), remark);
        //设置过桥费
        BigDecimal parkingFee = this.addOtherPrice(price, paymentParam.getParkingFee(), EOrderCostType.parkingFee.getType(), remark);
        //设置其他费用
        BigDecimal otherFee = this.addOtherPrice(price, paymentParam.getOtherFee(), EOrderCostType.otherFee.getType(), remark);
        return bridgeFee.add(highSpeedFee).add(parkingFee).add(otherFee);
    }

    // 获取司机信息
    public NettyUserOrderInfo vehicleResult(OaDVehicleGps gps, OaDUserInfo oaDUserInfo) {
        if (CheckUtil.objIsEmpty(gps)) {
            return null;
        }
        //获取车辆信息
        OaSysVehicle oaSysVehicle = sysVehicleMapper.selectById(gps.getVehId());
        if (!Objects.isNull(oaSysVehicle)) {
            // 查出车辆颜色
            Qw q = Qw.create();
            q.eq(OaSysDict.VALUE, oaSysVehicle.getVehColor()).eq(OaSysDict.TYPE, "vegicle_color_type");
            OaSysDict oaSysDict = oaSysDictMapper.selectOne(q);
            //根据司机车辆关联表查询出司机主键
//            Qw qw = Qw.create();
//            qw.eq(OaDDriverVehicle.VEHICLE_ID, oaSysVehicle.getVehicleId());
//            OaDDriverVehicle oaDDriverVehicle = driverVehicleMapper.selectOne(qw);
            if (CheckUtil.objIsNotEmpty(oaSysDict)) {
                //查询出司机信息
                OaDUser oaDUser = dUserMapper.selectById(gps.getDriverId());
                NettyUserOrderInfo result = new NettyUserOrderInfo();
                result.setVehNo(oaSysVehicle.getVehNo());
                result.setVehUserName(CheckUtil.strIsEmpty(oaDUser.getDriverName()) ? "胡先生" : oaDUser.getDriverName());
                result.setVehType(gps.getVehType());
                result.setVehUserPhone(oaDUser.getDriverPhone());
                result.setVehLat(gps.getLat());
                result.setVehLng(gps.getLng());
                result.setCarColor(oaSysDict.getLabel());
                //起点经纬度
                result.setOrderNo(gps.getOrderNo());
                Long driverId = oaDUser.getDriverId();
                result.setDriverId(String.valueOf(driverId));
                result.setEmergencyContact("<html></html>");
                result.setVehId(gps.getVehId() + "");
//                OaDUserInfo oaDUserInfo = dUserInfoMapper.selectOne(Qw.create().eq(OaDUserInfo.DRIVER_ID, driverId));
                if (!CheckUtil.objIsEmpty(oaDUserInfo)) {
                    result.setDriverLevel(CheckUtil.objIsEmpty(oaDUserInfo.getDriverLevel()) ? "1" : oaDUserInfo.getDriverLevel());
                    result.setTotalServiceScore(oaDUserInfo.getTotalServiceScore());
                    result.setOrderQuantityCompleted(oaDUserInfo.getOrderQuantityCompleted());
                    result.setBeenDriving(oaDUserInfo.getBeenDriving() + "年驾龄");
                    result.setAvatarFileId(oaDUser.getAvatarFileId() + "");
                } else {
                    result.setDriverLevel("1");
                    result.setTotalServiceScore(0);
                    result.setBeenDriving("0年驾龄");
                    result.setAvatarFileId("");
                }
                result.setBrand(this.getVehBrand(oaSysVehicle.getCode(), oaSysVehicle.getVehColor()));
                return result;
            }
        }
        return null;
    }


    /**
     * 封装订单信息
     *
     * @param order
     * @return
     */
    /**
     * 封装订单信息
     *
     * @param order
     * @return
     */
    public NettyDriverOrderInfo getOrderInfo(OaCOrder order, NettyDriverOrderInfo result) {
        try {
            result.setStartAddress(order.getStartAddress());
            result.setEndAddress(order.getEndAddress());
            result.setGpsId(order.getGpsId());
            result.setStartLng(order.getStartLng());
            result.setStartLat(order.getStartLat());
            result.setEndLng(order.getEndLng());
            result.setEndLat(order.getEndLat());
            result.setOrderNo(order.getOrderNo());
            result.setFlightNo(order.getFlightNo());
            result.setOrderStatus(order.getOrderStatus());
            result.setTime(CheckUtil.objIsEmpty(order.getOrderTime()) ? DateUtil.getChineseDate(null) : DateUtil.getChineseDate(order.getOrderTime()));
            result.setVehType(EvehicleType.findById(order.getVehicleType()).getValue());
            result.setTabType(ETabType.getType(order.getOrderNo()));
            result.setOrderType(ECallVehType.finaByValue(order.getOrderType()));
            result.setOrderTypeInt(order.getOrderType());
            result.setUploadId(order.getUploadId());
            return result;
        } catch (ParseException e) {
        }
        return null;
    }

    /**
     * 获取车辆品牌信息
     *
     * @return
     */
    public String getVehBrand(String code, Integer colorId) {
        String color = MessageConstant.BRANDCOLOR;
        String parentName = MessageConstant.BRAND;
        String childName = MessageConstant.BRANDCHILD;
        VehicleBrand vehicleBrand = mdictMapper.selectBrand(code);
        if (!CheckUtil.objIsEmpty(vehicleBrand)) {
            parentName = vehicleBrand.getParentName();
            childName = vehicleBrand.getChildName();
        }
        OaSysDict colorType = sysDictMapper.selectOne(Qw.create()
                .eq(OaSysDict.TYPE, "vegicle_color_type")
                .eq(OaSysDict.VALUE, colorId));
        if (!CheckUtil.objIsEmpty(colorType)) {
            color = colorType.getLabel();
        }
        return parentName + childName + "·" + color;
    }

    /**
     * 判断是否评价过
     *
     * @return
     */
    public int isEvaluation(Long id, int userType, String orderNo) {
        //验证是否评价
        OaOrderEvaluation oaOrderEvaluation = orderEvaluationMapper.selectOne(Qw.create()
                .eq(OaOrderEvaluation.ORDER_NO, orderNo)
                .eq(OaOrderEvaluation.USER_ID, id)
                .eq(OaOrderEvaluation.USER_TYPE, userType));
        int isEvaluation = ZERO.getType();
        if (!CheckUtil.objIsEmpty(oaOrderEvaluation)) {
            isEvaluation = ONE.getType();
        }
        return isEvaluation;
    }


    /**
     * 获取轨迹ID
     *
     * @param driverId
     * @return
     */
    public Long getGpsId(String driverId) {
        Long serviceId = getServiceId();
        Long tid = getTid(driverId);
        return amapService.getAmapGpdId(String.valueOf(serviceId), String.valueOf(tid));
    }

    /**
     * 获取服务Id
     *
     * @return
     */
    public Long getServiceId() {
        Long sid = 0L;
        List<OaSysGlobalConfig> oaSysGlobalConfigs = globalConfigMapper.selectList(null);
        if (CheckUtil.collectionIsEmpty(oaSysGlobalConfigs)) {
            log.error("获取全局配置表为空!");
            return sid;
        }
        OaSysGlobalConfig oaSysGlobalConfig = oaSysGlobalConfigs.get(0);
        return oaSysGlobalConfig.getGouldServiceId();
    }

    /**
     * 获取终端ID
     *
     * @return
     */
    public Long getTid(String driverId) {
        Long tid = 0L;
        //生成轨迹ID
        Qw qw = Qw.create();
        qw.select(OaDUserInfo.TID);
        qw.eq(OaDUserInfo.DRIVER_ID, driverId);
        OaDUserInfo userInfo = dUserInfoMapper.selectOne(qw);
        if (CheckUtil.objIsEmpty(userInfo)) {
            log.error("获取司机信息为空!");
            return tid;
        }
        return userInfo.getTid();
    }

    /**
     * 获取订单信息
     *
     * @param orderNo 订单号
     * @return
     */
    public OaCOrder queryOrderMessage(String orderNo) {
        String orderJson = redisCommon.getStr(RedisPrefixConstant.ORDER_OA_D_ORDER + orderNo);
        OaCOrder order = null;
        //如果redis中获取不到从数据库中获取
        if (CheckUtil.objIsEmpty(orderJson)) {
            order = selectOn(orderNo);
        } else {
            order = JSON.parseObject(orderJson, OaCOrder.class);
            OaCOrder orderVersion = selectOn(orderNo);
            order.setStartFee(orderVersion.getStartFee());
            order.setVersion(orderVersion.getVersion());
            order.setServiceId(getServiceId());
            order.setTid(getTid(order.getDriverId() + ""));
        }
        //如果最后还是空只能说,真没有找到
        if (CheckUtil.objIsEmpty(order)) {
            return null;
        }
        return order;
    }

    /**
     * 设置司机接单状态
     *
     * @param isOrder              true 已接单 false 未接单
     * @param acceptancOrderStatus true 已开始接单 false 未开始接单
     * @param driverId             司机ID
     * @param orderNo              如果已接单设置订单号,未接单设置空字符
     */
    public boolean setDriverIsOrderAndAcceptancOrderStatus(boolean isOrder, Boolean acceptancOrderStatus, Long driverId, String orderNo) {
        return this.setDriverIsOrderAndAcceptancOrderStatus(isOrder, acceptancOrderStatus, driverId, null, orderNo);
    }

    /**
     * 到达目的地释放司机
     *
     * @param isOrder  true 加锁 false 释放
     * @param driverId 司机ID
     * @param orderNo  订单号
     * @return
     */
    public boolean destinationEmancipationDriver(boolean isOrder, Long driverId, String orderNo) {
        OaDUserInfo oaDUserInfo = dUserInfoMapper.selectOne(Qw.create().eq(OaDUserInfo.DRIVER_ID, driverId));
        if (CheckUtil.objIsEmpty(oaDUserInfo)) {
            throw PangException.create(EErrorCode.noData);
        }
        String currentOrderNo = oaDUserInfo.getCurrentOrderNo();
        if (CheckUtil.strIsNotEmpty(currentOrderNo)) {
            // 判断要释放司机的订单,是不是当前司机接的订单
            if (currentOrderNo.equals(orderNo)) {
                log.info("DRIVER_HISTORY 司机被释放了,司机当前订单号:[{}],当前订单状态:[{}],司机ID:[{}]", orderNo, "到达目的地释放", driverId);
                return setDriverIsOrderAndAcceptancOrderStatus(isOrder, null, driverId, "");
            }
            // 如果不等于当前要释放的订单,直接返回
            return false;
        }
        log.info("DRIVER_HISTORY 司机被释放了,司机当前订单号:[{}],当前订单状态:[{}],司机ID:[{}]", orderNo, "到达目的地释放", driverId);
        return setDriverIsOrderAndAcceptancOrderStatus(isOrder, null, driverId, "");
    }

    /**
     * 设置司机接单状态
     */
    public boolean setDriverIsOrderAndAcceptancOrderStatus(boolean isOrder, Boolean AcceptancOrderStatus, Long driverId, OaDUserInfo oaDUserInfo, String orderNo) {

        oaDUserInfo = dUserInfoMapper.selectOne(Qw.create().eq(OaDUserInfo.DRIVER_ID, driverId));
        if (CheckUtil.objIsEmpty(oaDUserInfo)) {
            throw PangException.create(EErrorCode.noData);
        }
        //设置是否接单
        if (isOrder) {
            //已接单
            oaDUserInfo.setIsOrder(EDriverStatus.isOrderYes.getValue());
        } else {
            //未接单
            oaDUserInfo.setIsOrder(EDriverStatus.isOrderNo.getValue());
        }
        if (CheckUtil.objIsNotEmpty(AcceptancOrderStatus)) {
            //设置是否开始接单
            if (AcceptancOrderStatus) {
                //一开始接单
                oaDUserInfo.setAcceptancOrderStatus(EDriverStatus.acceptancOrderStatuYes.getValue());
            } else {
                //未开始接单
                oaDUserInfo.setAcceptancOrderStatus(EDriverStatus.acceptancOrderStatuNo.getValue());
            }
        }
        oaDUserInfo.setCurrentOrderNo(orderNo);
        if (dUserInfoMapper.updateById(oaDUserInfo) <= 0) {
            log.info("DRIVER_HISTORY 司机ID:[{}],更改司机信息失败", driverId);
            return false;
        }
        return true;
    }


    /**
     * 逻辑
     * 1. 如果总金额大于基础金额返回总金额
     * 2. 如果是司机扣除平台抽成后返回
     *
     * @param totalFee  总金额
     * @param baseFee   基础费
     * @param clientId  司机端/乘客端
     * @param drawRatio 平台抽成比例
     * @return
     */
    public BigDecimal getTotalFee(BigDecimal totalFee, BigDecimal baseFee, Integer clientId, BigDecimal drawRatio) {
        if (CheckUtil.objIsEmpty(baseFee)) {
            baseFee = new BigDecimal(ZERO.getTypeName());

        }
        if (CheckUtil.objIsEmpty(totalFee)) {
            totalFee = new BigDecimal(ZERO.getTypeName());
        }
        //判断要显示的金额
        BigDecimal showFee = new BigDecimal(ZERO.getTypeName());
        if (baseFee.doubleValue() > totalFee.doubleValue()) {
            showFee = baseFee;
        } else {
            showFee = totalFee;
        }

        //如果是司机进行抽成
        if (clientId.equals(EUserTypeNum.d.getValue())) {
            if (CheckUtil.objIsNotEmpty(drawRatio)) {
                BigDecimal multiply = showFee.multiply(drawRatio);
                showFee = showFee.subtract(multiply);
            }
        }
        return showFee.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 判断当前订单是否可以继续
     *
     * @param status
     */
    public void canTheOrderContinue(Integer status) {
        //判断当前订单是否可以继续
        EOrderStatus orderStatus = EOrderStatus.findById(status);
        //判断当前是否已取消
        if (EOrderStatus.isCancelOrder(orderStatus)) {
            throw PangException.create(EErrorCode.currentOrderCancelled);
        }
        //判断当前订单是否已支付
        if (EOrderStatus.isPay(orderStatus)) {
            throw PangException.create(EErrorCode.currentOrderIsPay);
        }
    }


    /**
     * 查询订单的其他订单
     *
     * @param orderNo
     * @return
     */
    public List<OaOrderOtherPrice> queryOtherPrice(String orderNo) {
        List<OaOrderOtherPrice> list = orderOtherPriceService.list(Qw.create().eq(OaOrderOtherPrice.ORDER_NO, orderNo));
        return list;
    }

    /**
     * 更改其他费用
     *
     * @param otherPrices
     * @return
     */
    public boolean updateOrderOtherPrice(List<OaOrderOtherPrice> otherPrices) {
        return orderOtherPriceService.updateBatchById(otherPrices);
    }
}
